package com.shop.gateway.filter;


import com.shop.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.logging.log4j.util.Strings;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 校验token合法性
 */
public class SportGlobalFilter implements Ordered, GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获得request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //鉴别是否登录
        if(request.getURI().getPath().contains("login")){
            //放行
            return chain.filter(exchange);
        }
        //获取token
        String token = request.getHeaders().getFirst("token");
        //判断token是否存在
        if(Strings.isBlank(token)){
            //不存在
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
//        //运动会id
//        String sportId = token.substring(0,token.indexOf("+"));
//        token = token.substring(token.indexOf("+")+1);
        //判断token是否过期
        try{
            //可能会解析失败
            //-1或0有效,1或2无效
            Claims claims = AppJwtUtil.getClaimsBody(token);
//            String schoolTenementId = claims.getId();
            int result = AppJwtUtil.verifyToken(claims);
            if(result==1||result==2){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                response.setComplete();
            }
//            //保存租户id
//            AccountUserBo.saveUser(BaseUtils.mapToObjectConverter(claims,AccountUserBo.class));

        }catch (Exception e){
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
